#!/bin/bash

#set -x

# checkSpringBootHealth.sh serviceName:port/path interval times

# checkSpringBootHealth.sh http://192.168.12.243:9032/media-publish/actuator/health 10 6


function doCheckHealth() {
    result=$(curl -k -vvv -s --connect-timeout 500 --max-time 2 $1 )
    if [[ $? -ne 0 ]] 
    then 
        echo "服务异常. url: $service_url, 服务返回：$result";
        return 1;
    fi
    return 0;
}

function checkHealth() {

    service_url=$1
    interval=$2
    times=$3

    log "开始检查服务健康状态. url: $service_url 最大检查次数：$times 检查间隔: $interval ";

    log "开始第 1 次检查... url: $service_url";
    doCheckHealth $1;
    if [[ $? -eq 0 ]] 
    then 
        log "服务正常，退出检查. url: $service_url";
        return 0;
    else 
        log "服务异常，等待 $interval 重新检查. url: $service_url";
    fi


    for i in $(seq 2 $3)
    do
        sleep $2;

        log "开始第 $i 次检查... url: $service_url";
        doCheckHealth $1;
        if [[ $? -eq 0 ]] 
        then 
            log "服务正常，退出检查. url: $service_url";
            return 0;
        else 
            log "服务异常，稍后重新检查. url: $service_url";
        fi
       
    done

    log "服务异常，达到最大检查次数，退出检查. url: $service_url";
    return 1;
}
 
function log() {
     echo "$(date +"%Y-%m-%d %H:%M:%S") $1";
}

checkHealth $@;
